<?php
/**
 * Created by sublime 3.
 * Auth: Inhere
 * Date: 14-10-28
 * Time: 10:35
 * Uesd: 主要功能是 hi
 * Response.php
 * @from windwalker https://github.com/ventoviro/windwalker
 */
namespace ulue\core\response;

use ulue\core\abstracts\AbstractCore;

class Response extends AbstractCore implements InterfaceResponse
{
    /**
     * @var integer the HTTP status code to send with the response.
     */
    private $_statusCode = 200;

    public $statusText = 'OK';

    public $version;

    /**
     * 标记是否已发送响应
     * @var boolean
     */
    public $isSent   = false;

    /**
     * 是否要浏览器缓存响应数据
     * @var bool
     */
    protected $cachable = false;

    /**
     * @var string
     */
    protected $mimeType = 'text/html';

    /**
     * @var string
     */
    protected $charset = 'utf-8';

    /**
     * 响应头信息
     * @var array
     */
    protected $headers = [];

    /**
     * 响应内容
     * @var null | string[]
     */
    protected $body = null;

    /**
     * 最后更改
     * @var null|\DataTime
     */
    protected $modifiedDate = null;

    const FORMAT_RAW   = 'raw';
    const FORMAT_HTML  = 'html';
    const FORMAT_JSON  = 'json';
    const FORMAT_JSONP = 'jsonp';
    const FORMAT_XML   = 'xml';

    public $format = self::FORMAT_HTML;

    public function __construct(array $options=[])
    {
        $this->propertys($options);
        $this->init();
    }

    public function init()
    {
        if ($this->version === null) {
            if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
                $this->version = '1.0';
            } else {
                $this->version = '1.1';
            }
        }
    }

////////////////////////////////////////// Handle //////////////////////////////////////////

    /**
     * Method to send the application response to the client.  All headers will be sent prior to the main
     * application output data.
     * @param   boolean $returnBody
     * @return  string
     */
    public function send($returnBody = false)
    {
        if ( $this->isSent ) {
            return;
        }

        // Send the content-type header.
        $this->setHeader('Content-Type', $this->mimeType . '; charset=' . $this->charset);

        // If the response is set to uncachable, we need to set some appropriate headers so browsers don't cache the response.
        // 如果不缓存响应数据,我们需要设置一些适当的头,这样浏览器就不会缓存响应数据。
        if (!$this->isCachable()) {
            // Expires in the past.
            $this->setHeader('Expires', 'Mon, 1 Jan 2001 00:00:00 GMT', true);

            // Always modified.
            $this->setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT', true);
            $this->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false);

            // HTTP 1.0
            $this->setHeader('Pragma', 'no-cache');
        } else {
            // Expires. 设置过期时间
            $this->setHeader('Expires', gmdate('D, d M Y H:i:s', time() + 900) . ' GMT');

            // Last modified. 最后修改
            if ($this->modifiedDate instanceof \DateTime) {
                $this->modifiedDate->setTimezone(new \DateTimeZone('UTC'));//UTC | PRC | Asia/Chongqing

                $this->setHeader('Last-Modified', $this->modifiedDate->format('D, d M Y H:i:s') . ' GMT');
            }
        }

        $this->sendHeaders();

        $this->isSent = true;

        if ($returnBody) {
            return $this->getBody();
        }

        echo $this->getBody();

        return '';
    }

    public function prepare()
    {
    }

    /**
     * Checks the accept encoding of the browser and compresses the data before
     * sending it to the client if possible.
     * @param string $encodings
     * @return  static
     */
    public function compress($encodings)
    {
        // Supported compression encodings.
        $supported = array(
            'x-gzip'    => 'gz',
            'gzip'      => 'gz',
            'deflate'   => 'deflate'
        );

        // Get the supported encoding.
        $encodings = array_intersect($encodings, array_keys($supported));

        // If no supported encoding is detected do nothing and return.
        if (empty($encodings)) {
            return $this;
        }

        // Verify that headers have not yet been sent, and that our connection is still alive.
        if ($this->headersIsSent() || !$this->checkConnectionAlive()) {
            return $this;
        }

        // Iterate through the encodings and attempt to compress the data using any found supported encodings.
        foreach ($encodings as $encoding) {
            if (($supported[$encoding] == 'gz') || ($supported[$encoding] == 'deflate')) {
                // Verify that the server supports gzip compression before we attempt to gzip encode the data.
                if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
                    continue;
                }

                // Attempt to gzip encode the data with an optimal level 4.
                $data = $this->getBody();
                $gzdata = gzencode($data, 4, ($supported[$encoding] == 'gz') ? FORCE_GZIP : FORCE_DEFLATE);

                // If there was a problem encoding the data just try the next encoding scheme.
                if ($gzdata === false) {
                    continue;
                }

                // Set the encoding headers.
                $this->setHeader('Content-Encoding', $encoding);
                $this->setHeader('X-Content-Encoded-By', 'Inhere');

                // Replace the output with the encoded data.
                $this->setBody($gzdata);

                // Compression complete, let's break out of the loop.
                break;
            }
        }

        return $this;
    }

    public function json()
    {
        $data = $this->getBody(true);
    }

////////////////////////////////////////// Head //////////////////////////////////////////

    /**
     * @return bool
     */
    public function headersIsSent()
    {
        return headers_sent();
    }

    public function checkConnectionAlive()
    {
        return (connection_status() === CONNECTION_NORMAL);
    }

    public function header($string, $replace = true, $code = null)
    {
        header($string, $replace, $code);

        return $this;
    }

    /**
     * Method to set a response header.  If the replace flag is set then all headers
     * with the given name will be replaced by the new one.  The headers are stored
     * in an internal array to be sent when the site is sent to the browser.
     * @param   string   $name     The name of the header to set.
     * @param   string   $value    The value of the header to set.
     * @param   boolean  $replace  True to replace any headers with the same name.
     * @return  object Response  Instance of $this to allow chaining.
     */
    public function setHeader($name, $value, $replace = false)
    {
        // Sanitize the input values.
        $name = (string) $name;
        $value = (string) $value;

        // If the replace flag is set, unset all known headers with the given name.
        if ($replace) {
            foreach ($this->headers as $key => $header) {
                if ($name == $header['name']) {
                    unset($this->headers[$key]);
                }
            }

            // Clean up the array as unsetting nested arrays leaves some junk.
            $this->headers = array_values($this->headers);
        }

        // Add the header to the internal array.
        $this->headers[] = array('name' => $name, 'value' => $value);

        return $this;
    }

    /**
     * send response Header info
     */
    public function sendHeaders()
    {
        if ( !$this->headersIsSent() ) {
            $statusCode = $this->getStatusCode();

            header("HTTP/{$this->version} $statusCode {$this->statusText}");

            foreach ( $this->getHeaders() as $header ) {
                if ('status' == strtolower($header['name'])) {
                    // 'status' headers indicate an HTTP status, and need to be handled slightly differently
                    $this->header(ucfirst(strtolower($header['name'])) . ': ' . $header['value'], null, (int) $header['value']);
                } else {
                    $this->header($header['name'] . ': ' . $header['value']);
                }
            }
        }

    }

    /**
     * Method to clear any set response headers.
     * @return  object Response  Instance of $this to allow chaining.
     */
    public function clearHeaders()
    {
        $this->headers = array();

        return $this;
    }

    /**
     * @param $headers
     * @return $this
     */
    public function setHeaders($headers)
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

////////////////////////////////////////// Body //////////////////////////////////////////

    /**
     * @param $content
     * @return $this
     */
    public function setBody($content)
    {
        $this->body = array((string) $content);

        return $this;
    }

    /**
     * @param bool $toArray
     * @return array|null|string
     */
    public function getBody($toArray=false)
    {
        return $toArray ? $this->body : implode( (array) $this->body );
    }

    /**
     * 在响应内容的前面添加数据
     * @param $data
     * @return string
     */
    public function prepend($data)
    {
        if ( is_array($this->body) ) {
            array_unshift($this->body, (string)$data);
        }

        return $this;
    }

    /**
     * 在响应内容的后面添加数据
     * @param $data
     * @return string
     */
    public function append($data)
    {
        if ( is_array($this->body) ) {
            array_push($this->body, (string) $data);
        }

        return $this;
    }

////////////////////////////////////////// Attributes //////////////////////////////////////////

    public function getStatusCode()
    {
        return $this->_statusCode;
    }

    public function setStatusCode($value, $text = null)
    {
        if ($value === null) {
            $value = 200;
        }

        $this->_statusCode = (int) $value;

        if ( $this->isInvalidCode($this->_statusCode) ) {
            throw new \DInvalidArgumentException("The HTTP status code is invalid: $value");
        }

        $this->statusText = StatusCodeText::get($this->_statusCode, $text);
    }

    /**
     * @return boolean whether this response has a valid [[statusCode]].
     */
    public function isInvalidCode($code)
    {
        return (int)$code < 100 || $code >= 600;
    }

    /**
     * @param $charset
     * @return $this
     */
    public function setCharset($charset)
    {
        $this->charset = $charset;

        return $this;
    }

    public function getCharset()
    {
        return $this->charset;
    }

    /**
     * getMimeType
     * @return  string
     */
    public function getMimeType()
    {
        return $this->mimeType;
    }

    /**
     * setMimeType
     * @param   string $mimeType
     * @return  static  Return self to support chaining.
     */
    public function setMimeType($mimeType)
    {
        $this->mimeType = $mimeType;

        return $this;
    }

    /**
     * getCachable
     * @param boolean $cachable
     * @return  boolean
     */
    public function isCachable($cachable = null)
    {
        if (is_bool($cachable)) {
            $this->cachable = $cachable;

            return $cachable;
        }

        return $this->cachable;
    }

    /**
     * @return  boolean
     */
    public function getCachable()
    {
        return $this->cachable;
    }


    /**
     * getModifiedDate
     *
     * @return  \DateTime
     */
    public function getModifiedDate()
    {
        return $this->modifiedDate;
    }

    /**
     * setModifiedDate
     *
     * @param   \DateTime $modifiedDate
     *
     * @return object Response  Return self to support chaining.
     */
    public function setModifiedDate(\DateTime $modifiedDate)
    {
        $this->modifiedDate = $modifiedDate;

        return $this;
    }

}